﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Drawing;
using System.Linq;
using System.IO;

namespace Opet
{
    public partial class frmMain : XtraForm
    {
        private DataTable Rows = new DataTable();
        private List<Customer> _customers = new List<Customer>();
        private List<Product> _products = new List<Product>();

        public frmMain()
        {
            InitializeComponent();
            Rows.Columns.Add("Bayi", typeof(string));
            Rows.Columns.Add("Ürün Cinsi", typeof(string));
            Rows.Columns.Add("Rafi.Satış Fiyatı", typeof(decimal));
            Rows.Columns.Add("Ötv", typeof(decimal));
            Rows.Columns.Add("Gelir Payı", typeof(decimal));
            Rows.Columns.Add("Servis Ücreti lt/tl", typeof(decimal));
            Rows.Columns.Add("Qpet Alış Fiyatı lt/tl", typeof(decimal));
            Rows.Columns.Add("Qpet Satış Fiyatı lt/tl", typeof(decimal));
            Rows.Columns.Add("Kar lt/tl", typeof(decimal));
            Rows.Columns.Add("Toplam Kar Marjı Satış Fiyatına göre yüzdesi", typeof(decimal));
            Rows.Columns.Add("Toplam Kar Marjı Alış Fiyatına göre yüzdesi", typeof(decimal));
            Rows.Columns.Add("Yürürlük Tarihi", typeof(DateTime));
            Rows.Columns.Add("Mal Alış Vadesi", typeof(int));
            Rows.Columns.Add("Net Satış Fiyatı", typeof(decimal));


            Rows.Rows.Add(null, "VADELİ (TÜPRAŞ)", null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);
            Rows.Rows.Add("MERSİN - TÜPRAŞ", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("MERSİN - TÜPRAŞ", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 21, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("GİRESUN - OPET", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("GİRESUN - OPET", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 19, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("KIRIKKALE TÜPRAŞ", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("KIRIKKALE TÜPRAŞ", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 17, null);
            Rows.Rows.Add("KIRIKKALE TÜPRAŞ", "FUEL OİL 6", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add("KIRIKKALE TÜPRAŞ", "GAZYAĞI", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("İZMİR ALİAĞA  TÜPRAŞ", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("İZMİR ALİAĞA  TÜPRAŞ", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 23, null);
            Rows.Rows.Add("İZMİR ALİAĞA  TÜPRAŞ", "FUEL OİL 4", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add("İZMİR ALİAĞA  TÜPRAŞ", "FUEL OİL 6", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add("İZMİR ALİAĞA  TÜPRAŞ", "GAZYAĞI", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("BATMAN TÜPRAŞ", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("BATMAN TÜPRAŞ", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 17, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("İZMİT YARIMCA", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 5, null);
            Rows.Rows.Add("İZMİT YARIMCA", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 21, null);
            Rows.Rows.Add("İZMİT YARIMCA", "FUEL OİL 4", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add("İZMİT YARIMCA", "FUEL OİL 6", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add("İZMİT YARIMCA", "GAZYAĞI", null, null, null, null, null, null, null, null, null, DateTime.Now, 3, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add(null, "PEŞİN (LUKOİL)", null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("SAMSUN TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add("SAMSUN TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("DÖRTYOL TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add("DÖRTYOL TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("HOPA TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add("HOPA TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 0, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add(null, "VADELİ (LUKOİL)", null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("SAMSUN TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);
            Rows.Rows.Add("SAMSUN TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("DÖRTYOL TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);
            Rows.Rows.Add("DÖRTYOL TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);
            Rows.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, DateTime.Now, null, null);

            Rows.Rows.Add("HOPA TERMİNAL", "KURŞUNSUZ BENZİN 95 OKTAN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);
            Rows.Rows.Add("HOPA TERMİNAL", "MOTORİN", null, null, null, null, null, null, null, null, null, DateTime.Now, 14, null);

            gridControl1.DataSource = Rows;
        }

        private int MaxSira(string Seri)
        {
            int sira = 0;
            using (Query q = new Query(Program.Session))
            {
                q.Add(string.Format("SELECT        ISNULL(MAX(sat_evrakno_sira), 0)  FROM            SATIS_SARTLARI WHERE        (sat_evrakno_seri = '{0}')", Seri));
                sira = q.ExecScaler<int>();
            }
            return (sira + 1);
        }

        private void CariYukle()
        {
            using (Query q = new Query(Program.Session))
            {
                q.Add("SELECT     cari_kod, cari_unvan1,cari_HalKomYuzdesi,cari_bolge_kodu  FROM         CARI_HESAPLAR where cari_bolge_kodu <> ''");
                DataTable dt = q.Fill();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    _customers.Add(new Customer()
                    {
                        Adi = dt.Rows[i]["cari_unvan1"].ToString(),
                        Kodu = dt.Rows[i]["cari_kod"].ToString(),
                        HalKomisyon = Cevir.Parse<decimal>(dt.Rows[i]["cari_HalKomYuzdesi"]) * 10,
                        BolgeKodu = dt.Rows[i]["cari_bolge_kodu"].ToString()
                    });
                }
            }
        }

        private void StokYukle()
        {
            using (Query q = new Query(Program.Session))
            {
                q.Add("SELECT     sto_kod, sto_isim,sto_gelirpayi  FROM         STOKLAR");
                DataTable dt = q.Fill();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    _products.Add(new Product()
                    {
                        Adi = dt.Rows[i]["sto_isim"].ToString(),
                        Kod = dt.Rows[i]["sto_kod"].ToString(),
                        GelirPayi = Cevir.Parse<decimal>(dt.Rows[i]["sto_gelirpayi"])
                    });
                }
            }
        }

        private void DepoYukle()
        {
            using (Query q = new Query(Program.Session))
            {
                q.Add("SELECT dep_no, dep_adi  FROM DEPOLAR");
                DataTable dt = q.Fill();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cmbDepo.Properties.Items.Add(new ComboItem() { DisplayValue = dt.Rows[i]["dep_adi"].ToString(), Value1 = dt.Rows[i]["dep_no"].ToString() });
                    cmbDepo.SelectedIndex = 0;
                }
            }
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            dteBelgeTarihi.DateTime = DateTime.Now;
            CariYukle();
            StokYukle();
            DepoYukle();

            gridControl1.ForceInitialize();
            gridView1.ColumnPanelRowHeight = 60;

            Font fnt = new Font("Taohama", 8, FontStyle.Regular);
            foreach (GridColumn item in gridView1.Columns)
            {
                item.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap;
                item.AppearanceHeader.Options.UseTextOptions = true;
                item.AppearanceHeader.Font = fnt;
                if (item.FieldName == "Ürün Cinsi")
                {
                    item.Width = 250;
                    //item.ColumnEdit = rpStok;
                    item.OptionsColumn.AllowEdit = false;
                    item.AppearanceCell.BackColor = Color.LightCyan;
                }
                else if (item.FieldName == "Bayi")
                {
                    item.Width = 105;
                    //item.ColumnEdit = rpCari;
                    item.OptionsColumn.AllowEdit = false;
                    item.AppearanceCell.BackColor = Color.LightCyan;
                }
            }

            gridView1.Columns[4].OptionsColumn.AllowEdit = false;
            gridView1.Columns[4].AppearanceCell.BackColor = Color.LightYellow;
            gridView1.Columns[6].OptionsColumn.AllowEdit = false;
            gridView1.Columns[6].AppearanceCell.BackColor = Color.LightBlue;
            gridView1.Columns[8].OptionsColumn.AllowEdit = false;
            gridView1.Columns[8].AppearanceCell.BackColor = Color.LightBlue;
            gridView1.Columns[9].OptionsColumn.AllowEdit = false;
            gridView1.Columns[9].AppearanceCell.BackColor = Color.LightCyan;
            gridView1.Columns[10].OptionsColumn.AllowEdit = false;
            gridView1.Columns[10].AppearanceCell.BackColor = Color.LightBlue;
            gridView1.Columns[11].ColumnEdit = rpTarih;
            gridView1.Columns[13].OptionsColumn.AllowEdit = false;
            gridView1.Columns[13].AppearanceCell.BackColor = Color.LightSteelBlue;

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (!string.IsNullOrEmpty(gridView1.GetRowCellDisplayText(i, gridView1.Columns[1]).ToString()) && !string.IsNullOrEmpty(gridView1.GetRowCellDisplayText(i, gridView1.Columns[0]).ToString()))
                {
                    Product pr = _products.Where(x => x.Adi == gridView1.GetRowCellDisplayText(i, gridView1.Columns[1]).ToString()).FirstOrDefault();
                    if (pr != null)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[4], pr.GelirPayi);
                    }
                }
            }
        }

        private void Hesapla(int row)
        {
            decimal satisfiyati = Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[2]));
            decimal otv = Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[3]));
            decimal gelirpayi = Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[4]));
            decimal servis_ucreti = Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[5]));
            decimal iskonto2 = 0m;//Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[13]));

            decimal alisfiyati = satisfiyati + otv + gelirpayi + servis_ucreti;
            gridView1.SetRowCellValue(row, gridView1.Columns[6], alisfiyati);

            decimal qpetsatisfiyati = Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[7]));

            if (qpetsatisfiyati > 0)
            {
                gridView1.SetRowCellValue(row, gridView1.Columns[8], qpetsatisfiyati - alisfiyati);
                gridView1.SetRowCellValue(row, gridView1.Columns[9], Cevir.Parse<decimal>((((qpetsatisfiyati - alisfiyati) / qpetsatisfiyati) * 100).ToString("n2")));
                if (alisfiyati > 0)
                {
                    gridView1.SetRowCellValue(row, gridView1.Columns[10], Cevir.Parse<decimal>((((qpetsatisfiyati - alisfiyati) / alisfiyati) * 100).ToString("n2")));
                }

                decimal netfiyat = qpetsatisfiyati - (qpetsatisfiyati / 100 * Cevir.Parse<decimal>(gridView1.GetRowCellDisplayText(row, gridView1.Columns[9])));
                netfiyat = netfiyat - (netfiyat / 100 * iskonto2);
                gridView1.SetRowCellValue(row, gridView1.Columns[13], netfiyat);
            }
        }


        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.VisibleIndex > 1 && e.Column.VisibleIndex != 6 && e.Column.VisibleIndex != 8 && e.Column.VisibleIndex != 9 && e.Column.VisibleIndex != 10 && e.Column.VisibleIndex != 14 && e.Column.VisibleIndex != 13)
            {
                Hesapla(e.RowHandle);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show("Kaydetmek istermisiniz ?", "", MessageBoxButtons.YesNo);
            if (rs == System.Windows.Forms.DialogResult.Yes)
            {
                EvrakKayit();

                StreamWriter sw = new StreamWriter(Application.StartupPath + "\\" + string.Format("{0}_{1}_{2}.xml", dteBelgeTarihi.DateTime.Day, dteBelgeTarihi.DateTime.Month, dteBelgeTarihi.DateTime.Year), false);
                string line = "";
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    for (int c = 2; c < gridView1.Columns.Count; c++)
                    {
                        line += gridView1.GetRowCellDisplayText(i, gridView1.Columns[c]).ToString() + ";";
                    }
                    sw.WriteLine(line);
                    line = "";
                }
                sw.Close();
            }
        }

        private void EvrakKayit()
        {
            string seri = "SAT";
            int sira = MaxSira("SAT");

            List<SatisSarti> _lines = new List<SatisSarti>();
            SatisSarti st = null;
            int satir = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (gridView1.GetRowCellValue(i, gridView1.Columns[0]) != DBNull.Value && gridView1.GetRowCellValue(i, gridView1.Columns[1]) != DBNull.Value && gridView1.GetRowCellValue(i, gridView1.Columns[7]) != DBNull.Value)
                {
                    var list = _customers.Where(x => x.BolgeKodu == gridView1.GetRowCellDisplayText(i, gridView1.Columns[0]).ToString()).ToList();
                    foreach (var cari in list)
                    {
                        st = new SatisSarti();
                        if (gridView1.GetRowCellValue(i, gridView1.Columns[11]) != DBNull.Value)
                        {
                            st.BaslangicTarihi = Cevir.Parse<DateTime>(gridView1.GetRowCellValue(i, gridView1.Columns[11]));
                            st.BaslangicTarihi = new DateTime(st.BaslangicTarihi.Year, st.BaslangicTarihi.Month, st.BaslangicTarihi.Day);
                        }
                        else
                        {
                            st.BaslangicTarihi = DateTime.Now;
                        }
                        st.BelgeNo = "";
                        st.BitisTarihi = new DateTime(1900, 1, 1);
                        st.BurutFiyat = Cevir.Parse<decimal>(gridView1.GetRowCellValue(i, gridView1.Columns[7]));

                        st.CariKodu = cari.Kodu;
                        st.DepoNo = Cevir.Parse<int>(((ComboItem)cmbDepo.SelectedItem).Value1);
                        st.DovizCinsi = 0;
                        st.FiyatNo = 1;
                        st.Iskonto1 = Cevir.Parse<decimal>(gridView1.GetRowCellValue(i, gridView1.Columns[9]));
                        st.Iskonto2 = cari.HalKomisyon;
                        st.Iskonto3 = 0;
                        st.Iskonto4 = 0;
                        st.Iskonto5 = 0;
                        st.Iskonto6 = 0;

                        if (gridView1.GetRowCellValue(i, gridView1.Columns[11]) != DBNull.Value)
                        {
                            st.OdemePlani = Cevir.Parse<int>(gridView1.GetRowCellValue(i, gridView1.Columns[11])) * -1;
                        }
                        else
                        {
                            st.OdemePlani = 0;
                        }

                        st.Satir = satir;
                        st.Seri = seri;
                        st.Sira = sira;

                        Product pr = _products.Where(x => x.Adi == gridView1.GetRowCellDisplayText(i, gridView1.Columns[1]).ToString()).FirstOrDefault();
                        if (pr != null)
                        {
                            st.StokKodu = pr.Kod;
                        }
                        st.Tarih = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

                        _lines.Add(st);
                    }

                    satir++;
                }
            }

            if (_lines.Count > 0)
            {
                Mikro mikro = new Mikro();
                mikro.SatisSartiEkle(_lines.ToArray());
                MessageBox.Show("Kayıt Tamamlandı !");
            }
        }

        private void cmbDepo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                gridControl1.Focus();
                gridView1.FocusedRowHandle = 0;
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "";
            dlg.Filter = "Excell|*.xls";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                gridView1.ExportToXls(dlg.FileName);
            }
        }

        private void dteBelgeTarihi_DateTimeChanged(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\" + string.Format("{0}_{1}_{2}.xml", dteBelgeTarihi.DateTime.Day, dteBelgeTarihi.DateTime.Month, dteBelgeTarihi.DateTime.Year)))
            {
                StreamReader sr = new StreamReader(Application.StartupPath + "\\" + string.Format("{0}_{1}_{2}.xml", dteBelgeTarihi.DateTime.Day, dteBelgeTarihi.DateTime.Month, dteBelgeTarihi.DateTime.Year));
                string[] fields;
                int row = 0;
                while (sr.Peek() > -1)
                {
                    fields = sr.ReadLine().Split(';');
                    for (int i = 0; i < fields.Length - 1; i++)
                    {
                        if (string.IsNullOrEmpty(fields[i]))
                        {
                            gridView1.SetRowCellValue(row, gridView1.Columns[i + 2], Cevir.Parse<decimal>(fields[i]));
                        }
                        else
                        {
                            gridView1.SetRowCellValue(row, gridView1.Columns[i + 2], fields[i]);
                        }
                    }
                    row++;
                }
                sr.Close();
            }
            else
            {
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    for (int c = 2; c < gridView1.Columns.Count; c++)
                    {
                        if (c == 11)
                        {
                            gridView1.SetRowCellValue(i, gridView1.Columns[c], DateTime.Now);
                        }
                        else
                            gridView1.SetRowCellValue(i, gridView1.Columns[c], 0);
                    }
                }
            }

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (!string.IsNullOrEmpty(gridView1.GetRowCellDisplayText(i, gridView1.Columns[1]).ToString()) && !string.IsNullOrEmpty(gridView1.GetRowCellDisplayText(i, gridView1.Columns[0]).ToString()))
                {
                    Product pr = _products.Where(x => x.Adi == gridView1.GetRowCellDisplayText(i, gridView1.Columns[1]).ToString()).FirstOrDefault();
                    if (pr != null)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[4], pr.GelirPayi);
                    }
                }
            }
        }

        private void dteBelgeTarihi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cmbDepo.Focus();
            }
        }
    }
}
